#include "HttpWorker.h"
#include <QNetworkRequest>
#include <QEventLoop>


HttpWorker::HttpWorker(const QUrl &url, const QJsonObject & jsParam, QObject *parent)
    : QObject(parent), m_url(url), m_jsParam(jsParam)
{
    setAutoDelete(true);
}

void HttpWorker::run()
{
    QNetworkAccessManager manager;
    QNetworkRequest request(m_url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");

    QNetworkReply *reply = manager.post(
        request,
        QJsonDocument(m_jsParam).toJson()
        );

    QEventLoop loop; //阻塞等待返回
    QObject::connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();

    QString path = m_url.path();
    if (path.contains(url_def::login))
    {
        if(reply->error() != QNetworkReply::NoError)
        {
             qDebug() << "返回错误";
            return;
        }

        // 检查路径是否包含字段
        QByteArray responseData = reply->readAll();
         qDebug() << responseData.toStdString();
         emit requestLoginFinished(responseData);
    }
    else if(path.contains(url_def::getpersoninfolist))
    {
        if(reply->error() != QNetworkReply::NoError)
        {
            qDebug() << "返回错误";
            return;
        }

        // 检查路径是否包含字段
        QByteArray responseData = reply->readAll();
        qDebug() << responseData.toStdString();
        emit requestGetPersonInfoListFinished(responseData);
    }
    else
    {

    }
    reply->deleteLater();
}
